/*eslint-disable*/
import { ElMessage } from "element-plus";
import pubsub from "pubsub-js"
import mainApi from "@/api/mainApi";

function readJson(ElMessage, fun) {
    window.myApi.fs.readFile(window.myApi.jsonPath, "utf8", (err, data) => {
        if (err) {
            console.error("Error reading file:", err);
            ElMessage({
                message: "store文件夹配置有误!请重新配置后再启动Waigua+",
                type: "error",
                duration: 10000
            });
            this.writeDailyLog("store文件夹配置有误")
        } else {
            try {
                // 通过回调函数操作json中的数据
                fun(JSON.parse(data))
            } catch (parseError) {
                console.error("Error parsing JSON:", parseError);
                ElMessage({
                    message: "JSON文件出错:" + parseError,
                    type: "error",
                    duration: 10000
                });
                this.writeDailyLog("JSON文件出错:" + parseError)
            }
        }
    });
}

// 面补重命名函数
function faceRename(folderPath, waiguaFiles, waiguaPath) {
    console.log(folderPath, waiguaFiles, waiguaPath);
    // 检测编号是否一致
    let numIsSame = folderPath.substring(0, 4) === extractNumbersAndFloats(waiguaFiles[0])[0]
    // 不一致则重命名iff文件夹
    if (numIsSame) return waiguaFiles

    // 执行重命名
    waiguaFiles.forEach(file => {
        // 原文件路径
        let oriPath = window.myApi.path.join(waiguaPath, file)
        file = file.replace(/\d+/g, folderPath.substring(0, 4))
        // 目标文件路径
        let tarPath = window.myApi.path.join(waiguaPath, file)
        window.myApi.fs.rename(oriPath, tarPath, (err) => {
            // 失败
            if (err) {
                ElMessage({ message: `变更${oriPath}时失败,错误为:${err}`, type: "error" });
                mainApi.writeDailyLog(`变更${oriPath}时失败,错误为:${err}` + "--upLoadApi.js")
                return
            }
            // console.log(`变更${oriPath}成功,已重命名为${tarPath}`);
            // 成功
            mainApi.writeDailyLog(`变更${oriPath}成功,已重命名为${tarPath}` + "--upLoadApi.js")
        })
    });

    // 目标文件路径
    let newWaiguaFiles = []
    waiguaFiles.forEach(file => {
        file = file.replace(/\d+/g, folderPath.substring(0, 4))
        newWaiguaFiles.push(file)
    });

    return newWaiguaFiles
}

function extractNumbersAndFloats(text) {
    // 使用正则表达式匹配所有整数和浮点数
    const regex = /\d+(?:\.\d+)?/g;
    // 执行匹配
    const matches = text.match(regex);
    // 将匹配到的数字字符串数组转换为数字数组
    const numbers = matches ? matches.map(Number) : [];
    return numbers;
}

export default {
    // 读取json中的路径
    readJson(ElMessage, fun) {
        window.myApi.fs.readFile(window.myApi.jsonPath, "utf8", (err, data) => {
            if (err) {
                console.error("Error reading file:", err);
                ElMessage({
                    message: "store文件夹配置有误!请重新配置后再启动Waigua+",
                    type: "error",
                    duration: 10000
                });
                this.writeDailyLog("store文件夹配置有误")
            } else {
                try {
                    // 通过回调函数操作json中的数据
                    fun(JSON.parse(data))
                } catch (parseError) {
                    console.error("Error parsing JSON:", parseError);
                    ElMessage({
                        message: "JSON文件出错:" + parseError,
                        type: "error",
                        duration: 10000
                    });
                    this.writeDailyLog("JSON文件出错:" + parseError)
                }
            }
        });
    },
    // mod移动总起
    modReplace(folderPath, modName) {
        console.log(folderPath, modName);
        // mod类型区分
        let type = this.TypeDistinction(folderPath)
        this.replaceFunctionList[type](folderPath, modName, this.copyFile, this.writeDailyLog)
    },
    // 类型区分函数
    TypeDistinction(path) {
        let typeList = ["jersey", "court", "blacktop", "packing", "face", "animation", "exe", "scoreboard"]
        let type
        typeList.forEach(element => {
            if (path.indexOf(element) != -1) {
                type = element
            }
        });
        return type
    },
    // 文件复制函数
    copyFile(modName, fileList, ori_path, tar_path, writeDailyLog) {
        fileList.forEach(async file => {
            // 源文件路径
            const sourceFilePath = window.myApi.path.join(ori_path, file);
            // 目标文件路径
            const destinationFilePath = window.myApi.path.join(tar_path, file);
            // 文件名称
            let fileName = sourceFilePath.split("\\")[sourceFilePath.split("\\").length - 1];

            writeDailyLog(`文件复制:\n源文件路径:${sourceFilePath}\n目标文件路径:${destinationFilePath}\n文件名称:${fileName}`)
            // console.log(sourceFilePath, destinationFilePath);

            // 移动文件
            // await window.myApi.fs.copyFile(sourceFilePath, destinationFilePath,
            //     (err) => {
            //         if (err) {
            //             console.error('移动文件失败：', err);
            //             ElMessage({
            //                 message: `${modName}的 ${file} 移动失败：${err}`,
            //                 type: "error",
            //                 duration: 10000
            //             })
            //         } else {
            //             // console.log(`${modName}的 ${file} 移动成功`);
            //             ElMessage({
            //                 message: `${modName}的 ${file} 移动成功`,
            //                 type: "success",
            //                 duration: 1000
            //             })
            //         }
            //     });
            window.myApi.copyFileWithProgress(sourceFilePath, destinationFilePath, (progress) => {
                pubsub.publish("progressRenew", {
                    title: fileName, progress
                })
            }).then(() => {
                console.log(`${modName}的 ${file} 移动成功`);
                ElMessage({
                    message: `${modName}的 ${file} 移动成功`,
                    type: "success",
                    duration: 1000
                })
                writeDailyLog(`${modName}的 ${file} 移动成功`)
            })
                .catch((err) => {
                    console.error('移动文件失败：', err);
                    ElMessage({
                        message: `${modName}的 ${file} 移动失败：${err}`,
                        type: "error",
                        duration: 10000
                    })
                    writeDailyLog(`${modName}的 ${file} 移动失败：${err}`)
                });
        });
    },
    // 不同类型的mod替换方法
    replaceFunctionList: {
        jersey(folderPath, modName, copyFile, writeDailyLog) {
            // 传输至waigua部分
            let waiguaPath = folderPath
            let waiguaFiles = window.myApi.fs.readdirSync(folderPath);
            let toWaigua = [waiguaFiles[2], waiguaFiles[3]]

            // 传输至clothing
            let clothingPath = window.myApi.path.join(folderPath, "clothing")
            let toClothing = window.myApi.fs.readdirSync(clothingPath);
            console.log(toWaigua, toClothing);

            // 开启进度面板
            let nameItem = folderPath.split("\\")
            pubsub.publish("progressPanelShow", {
                show: true,
                title: `${nameItem[nameItem.length - 2]}-${nameItem[nameItem.length - 1]}`,
                list: toWaigua.concat(toClothing)
            })

            // 读取传输目标文件夹
            window.myApi.fs.readFile(window.myApi.jsonPath, "utf8", (err, data) => {
                try {
                    let targetWaiguaPath = JSON.parse(data).waigua
                    let targetClothingPath = window.myApi.path.join(targetWaiguaPath, "clothing")

                    // waigua部分
                    copyFile(modName, toWaigua, waiguaPath, targetWaiguaPath, writeDailyLog)

                    // clothing部分
                    copyFile(modName, toClothing, clothingPath, targetClothingPath, writeDailyLog)
                } catch (err) {
                    console.error(err);
                    writeDailyLog(`传输文件出错：${err}`)
                }
            });

        },
        court(folderPath, modName, copyFile, writeDailyLog) {
            // 传输至waigua部分
            let waiguaPath = folderPath
            let waiguaFiles = [window.myApi.fs.readdirSync(folderPath)[0]];

            // 开启进度面板
            let nameItem = folderPath.split("\\")
            pubsub.publish("progressPanelShow", {
                show: true,
                title: `${nameItem[nameItem.length - 2]}-${nameItem[nameItem.length - 1]}`,
                list: waiguaFiles
            })

            window.myApi.fs.readFile(window.myApi.jsonPath, "utf8", (err, data) => {
                try {
                    let targetWaiguaPath = JSON.parse(data).waigua
                    // waigua路径为空警告
                    if (targetWaiguaPath === "") {
                        ElMessage({
                            message: "waigua路径出错,",
                            type: "error"
                        })
                        writeDailyLog(`waigua路径出错`)
                        return
                    }
                    // waigua部分
                    copyFile(modName, waiguaFiles, waiguaPath, targetWaiguaPath, writeDailyLog)
                } catch (err) {
                    console.error(err);
                    writeDailyLog(`传输文件出错：${err}`)
                }

            });
        },
        scoreboard(folderPath, modName, copyFile, writeDailyLog) {
            // 传输至waigua部分
            let waiguaPath = folderPath
            let waiguaFiles = [window.myApi.fs.readdirSync(folderPath)[0]];

            // 开启进度面板
            let nameItem = folderPath.split("\\")
            pubsub.publish("progressPanelShow", {
                show: true,
                title: `${nameItem[nameItem.length - 2]}-${nameItem[nameItem.length - 1]}`,
                list: waiguaFiles
            })

            window.myApi.fs.readFile(window.myApi.jsonPath, "utf8", (err, data) => {
                try {
                    let targetWaiguaPath = JSON.parse(data).waigua
                    // waigua路径为空警告
                    if (targetWaiguaPath === "") {
                        ElMessage({
                            message: "waigua路径出错,",
                            type: "error"
                        })
                        writeDailyLog(`waigua路径出错`)
                        return
                    }
                    // waigua部分
                    copyFile(modName, waiguaFiles, waiguaPath, targetWaiguaPath, writeDailyLog)
                } catch (err) {
                    console.error(err);
                    writeDailyLog(`传输文件出错：${err}`)
                }

            });
        },
        face(folderPath, modName, copyFile, writeDailyLog) {
            // 传输至waigua部分
            let waiguaPath = folderPath
            console.log(waiguaPath);
            let waiguaFiles = window.myApi.fs.readdirSync(folderPath).filter(folder => folder != "preview")

            // 重命名检测
            waiguaFiles = faceRename(modName, waiguaFiles, waiguaPath)

            // 开启进度面板
            let nameItem = folderPath.split("\\")
            pubsub.publish("progressPanelShow", {
                show: true,
                title: `${nameItem[nameItem.length - 2]}-${nameItem[nameItem.length - 1]}`,
                list: waiguaFiles
            })

            window.myApi.fs.readFile(window.myApi.jsonPath, "utf8", (err, data) => {
                try {
                    let targetWaiguaPath = JSON.parse(data).waigua
                    // waigua路径为空警告
                    if (targetWaiguaPath === "") {
                        ElMessage({
                            message: "waigua路径出错,",
                            type: "error"
                        })
                        writeDailyLog(`waigua路径出错`)
                        return
                    }
                    // console.log(modName, waiguaFiles, waiguaPath, targetWaiguaPath);
                    // waigua部分
                    copyFile(modName, waiguaFiles, waiguaPath, targetWaiguaPath, writeDailyLog)
                } catch (err) {
                    console.error(err);
                    writeDailyLog(`传输文件出错：${err}`)
                }

            });
        },
        blacktop(folderPath, modName, copyFile, writeDailyLog) {
            // 传输至waigua部分
            let waiguaPath = folderPath
            let waiguaFiles = [window.myApi.fs.readdirSync(folderPath)[1]];

            // 开启进度面板
            let nameItem = folderPath.split("\\")
            pubsub.publish("progressPanelShow", {
                show: true,
                title: `${nameItem[nameItem.length - 2]}-${nameItem[nameItem.length - 1]}`,
                list: waiguaFiles
            })

            window.myApi.fs.readFile(window.myApi.jsonPath, "utf8", (err, data) => {
                try {
                    let targetWaiguaPath = JSON.parse(data).waigua
                    // waigua路径为空警告
                    if (targetWaiguaPath === "") {
                        ElMessage({
                            message: "waigua路径出错,",
                            type: "error"
                        })
                        writeDailyLog(`waigua路径出错`)
                        return
                    }
                    // waigua部分
                    copyFile(modName, waiguaFiles, waiguaPath, targetWaiguaPath, writeDailyLog)
                } catch (err) {
                    console.error(err);
                    writeDailyLog(`传输文件出错：${err}`)
                }

            });
        },
        packing(folderPath, modName, copyFile, writeDailyLog) {
            // 传输至waigua部分
            let waiguaPath = window.myApi.path.join(folderPath, "waigua")
            let waiguaFiles = window.myApi.fs.readdirSync(waiguaPath);

            // 传输至clothing部分
            let clothingPath = window.myApi.path.join(folderPath, "clothing")
            let clothFiles = window.myApi.fs.readdirSync(clothingPath);

            // 开启进度面板
            let nameItem = folderPath.split("\\")
            pubsub.publish("progressPanelShow", {
                show: true,
                title: `${nameItem[nameItem.length - 2]}-${nameItem[nameItem.length - 1]}`,
                list: waiguaFiles.concat(clothFiles)
            })

            // 读取传输目标文件夹
            window.myApi.fs.readFile(window.myApi.jsonPath, "utf8", (err, data) => {
                try {
                    let targetWaiguaPath = JSON.parse(data).waigua
                    let targetClothingPath = window.myApi.path.join(targetWaiguaPath, "clothing")

                    // waigua部分
                    copyFile(modName, waiguaFiles, waiguaPath, targetWaiguaPath, writeDailyLog)

                    // clothing部分
                    copyFile(modName, clothFiles, clothingPath, targetClothingPath, writeDailyLog)
                } catch (err) {
                    console.error(err);
                    writeDailyLog(`传输文件出错：${err}`)
                }
            });
        },
        animation(folderPath, modName, copyFile, writeDailyLog) {
            // 传输至waigua部分
            let waiguaPath = folderPath
            let waiguaFiles = [window.myApi.fs.readdirSync(folderPath)[0]];

            // 开启进度面板
            let nameItem = folderPath.split("\\")
            pubsub.publish("progressPanelShow", {
                show: true,
                title: `${nameItem[nameItem.length - 2]}-${nameItem[nameItem.length - 1]}`,
                list: waiguaFiles
            })

            window.myApi.fs.readFile(window.myApi.jsonPath, "utf8", (err, data) => {
                try {
                    let targetWaiguaPath = JSON.parse(data).waigua
                    // waigua路径为空警告
                    if (targetWaiguaPath === "") {
                        ElMessage({
                            message: "waigua路径出错,",
                            type: "error"
                        })
                        writeDailyLog(`waigua路径出错`)
                        return
                    }
                    // waigua部分
                    copyFile(modName, waiguaFiles, waiguaPath, targetWaiguaPath, writeDailyLog)
                } catch (err) {
                    console.error(err);
                    writeDailyLog(`传输文件出错：${err}`)
                }

            });
        },
        exe(folderPath, modName, copyFile, writeDailyLog) {
            // 传输至waigua部分
            let waiguaPath = folderPath
            let waiguaFiles = [window.myApi.fs.readdirSync(folderPath)[0]];

            // 开启进度面板
            let nameItem = folderPath.split("\\")
            pubsub.publish("progressPanelShow", {
                show: true,
                title: `${nameItem[nameItem.length - 2]}-${nameItem[nameItem.length - 1]}`,
                list: waiguaFiles
            })

            window.myApi.fs.readFile(window.myApi.jsonPath, "utf8", (err, data) => {
                try {
                    let targetWaiguaPath = window.myApi.path.dirname(JSON.parse(data).waigua)
                    // waigua路径为空警告
                    if (targetWaiguaPath === "") {
                        ElMessage({
                            message: "waigua路径出错,",
                            type: "error"
                        })
                        writeDailyLog(`waigua路径出错`)
                        return
                    }
                    // waigua部分
                    copyFile(modName, waiguaFiles, waiguaPath, targetWaiguaPath, writeDailyLog)
                } catch (err) {
                    console.error(err);
                    writeDailyLog(`传输文件出错：${err}`)
                }

            });
        },
    },
    // 日志填写函数
    writeDailyLog(logData) {
        readJson(ElMessage, (data) => {
            // 读取当前日期
            const currentDate = new Date();
            const year = currentDate.getFullYear();
            const month = currentDate.getMonth() + 1;
            const day = currentDate.getDate();
            // 拼接日志文件名
            let logPath =
                window.myApi.path.join(data.fileHouse, 'log', `${year}${month}${day}log.txt`);
            // console.log(logPath);
            // 写入日志
            window.myApi.fs.appendFileSync(
                logPath,
                `${new Date().toLocaleString()} - ${logData}\n`
            );
        })
    }

}